package com.liaozibo.demo.seckill.support.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.Transaction;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;

@Component
@Slf4j
public class RedisUtils {
    private static String decrStockSHA;

    @Autowired
    private JedisPool jedisPool;


    @PostConstruct
    public void init() throws IOException {
        ClassPathResource resource = new ClassPathResource("/lua/decrStock.lua");
        File file = resource.getFile();
        String decrStockScript = new String(Files.readAllBytes(file.toPath()));
        try (Jedis jedis = jedisPool.getResource()){
            decrStockSHA = jedis.scriptLoad(decrStockScript);
            log.info("redis script sha[decrStock.lua]: " + decrStockSHA);
        }
    }

    public String get(String key) {
        try (Jedis jedis = jedisPool.getResource()) {
            return jedis.get(key);
        }
    }

    public void set(String key, String value) {
        try (Jedis jedis = jedisPool.getResource()) {
            jedis.set(key, value);
        }
    }

    public void set(String key, String value, int expireTime) {
        try (Jedis jedis = jedisPool.getResource()) {
            Transaction transaction = jedis.multi();
            transaction.set(key, value);
            transaction.expire(key, expireTime);
            transaction.exec();
        }
    }

    /**
     * 扣减库存
     * @param code 商品编号
     * @param buyNum 购买数量
     * @return 1 扣减成功，0 扣减失败
     * */
    public Long decrStock(String code, int buyNum) {
        try (Jedis jedis = jedisPool.getResource()) {
            Object obj = jedis.evalsha(decrStockSHA, 2, "stock_" + code, String.valueOf(buyNum));
            return (Long)obj;
        }
    }
}
